<template>
  <el-card class="attr">
    <el-form inline>
      <el-form-item label="一级分类">
        <el-select placeholder="请选择一级分类" v-model="category1Id">
        <el-option :label="c1.name" :value="c1.id"  v-for="c1 in getCategory1List" :key="c1.id"/>
         
        </el-select>
      </el-form-item>

      <el-form-item label="二级分类">
        <el-select placeholder="请选择二级分类" v-model="category2Id" >
          <el-option :label="c2.name" :value="c2.id"  v-for="c2 in getCategory2List" :key="c2.id"/>
        </el-select>
      </el-form-item>

      <el-form-item label="三级分类">
        <el-select placeholder="请选择三级分类"  v-model="category3Id">
          <el-option :label="c3.name" :value="c3.id"  v-for="c3 in getCategory3List" :key="c3.id"/>

 
        </el-select>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "CategorySelector",
};
</script>

<script lang="ts" setup>
import  {getCategory1ListApi,getCategory2ListApi,getCategory3ListApi} from '@/api/product/category'
import { onMounted, ref } from 'vue';
import type { CategoryList } from "@/api/product/model/categoryModel";
import { watch } from 'vue';

const getCategory1List=ref<CategoryList>([])
const getCategory2List=ref<CategoryList>([])
const getCategory3List=ref<CategoryList>([])
  const category1Id=ref()
  const category2Id=ref()
  const category3Id=ref()

onMounted(async()=>{
  getCategory1List.value= await getCategory1ListApi()

})
watch(category1Id,async(newVal)=>{
  getCategory2List.value=await getCategory2ListApi(newVal)
  category2Id.value = undefined;
  category3Id.value = undefined;
  getCategory3List.value = []; //一级分类发生变化时,二级会有对应的数据,三级此时没数据

})
watch(category2Id,async(newVal)=>{
  // console.log(newVal)
  if(!newVal)return   // 重新选择一级分类时，会将二级分类id置为undefined，此时触发watch，导致请求的二级分类id没有值，请求失败

  getCategory3List.value=await getCategory3ListApi(newVal)
  category3Id.value = undefined;
})


</script>

<style scoped>
/* 深度选择器 */
.attr :deep(.el-form-item) {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
